package cn.suxiaoxiang.suwebverify.util;

import cn.suxiaoxiang.suwebverify.table.DatabaseTable;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
 * SQLiteDownloader - 用于管理 SQLite 数据库连接去
 *
 * @author 程序员-Su_xiaoxiang
 * @date 2025/4/7 18:00
 */
public class SQLiteManager {
    private static Connection connection;
    private static JavaPlugin plugin;

    // 构造函数，接收插件实例
    public SQLiteManager(JavaPlugin plugin) {
        SQLiteManager.plugin = plugin;
    }

    // 连接数据库
    public static void connect() {
        try {
            // 确保数据库目录存在
            File dataFolder = plugin.getDataFolder();
            if (!dataFolder.exists()) {
                dataFolder.mkdirs();
            }

            // 设置数据库文件路径
            File dbFile = new File(dataFolder, "database.db");

            // 加载 SQLite 驱动并连接数据库
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile.getAbsolutePath());
            plugin.getLogger().info("SQLite 已连接！");

            // 创建表格
            DatabaseTable dbHelper = new DatabaseTable(plugin);
            dbHelper.createPlayerTables(connection);

        } catch (Exception e) {
            plugin.getLogger().severe("连接 SQLite 时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }


    // 关闭连接
    public static void close() {
        try {
            if (connection != null) {
                connection.close();
                plugin.getLogger().info("SQLite 连接已关闭！");
            }
        } catch (SQLException e) {
            plugin.getLogger().severe("关闭 SQLite 连接时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 获取数据库连接
    public static Connection getConnection() {
        return connection;
    }
}
